package com.gyw.myapplication.compare;

/**
 * Created by Administrator on 2018/12/7.
 */

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.gyw.myapplication.xyaxis.AxisBackgroundByDivider;

import java.util.ArrayList;
import java.util.List;

/**
 * 整体由一个LinearLayout+RecyclerView构成
 * LinearLayout:内部填充表格左上角的CornerCellView，以及填充右边的RecyclerView(item为多个TopCellView)（决定列）
 *
 * 下面的大块RecyclerView:item数目决定行:每个Item布局均分为两种：
 *                          1.横款整个行的GroupView
 *                          2.由等同LinerLayout填充布局的leftcellview+recyclerview(item为row的具体cell)构成
 */
public class TableView extends LinearLayout implements TableRowView.HorizontalScrollChangedListener,TableAdapter.DataChangedHelper {
    private TableAdapter tableAdapter;
    private Context context;
    //存放所有需要同步横向滑动的RecyclerView
    protected List<TableRowView> rowViews = new ArrayList<TableRowView>();


    public TableView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context=context;
    }


    public void setAdapter(TableAdapter tableAdapter){
        tableAdapter.registerDataChanged(this);
        this.tableAdapter=tableAdapter;
        initView();
    }

    private void initView(){
        initHead();
        initBody();
    }
    //head由左上角第一个cell(制表头)+table列头构成
    private void initHead(){

        LinearLayout headContainer=new LinearLayout(context);
        LinearLayout.LayoutParams headContainerLp=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
        addView(headContainer,headContainerLp);


        FrameLayout cornerCellContainer=new FrameLayout(context);
        LinearLayout.LayoutParams cornerCellContainerLp=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.MATCH_PARENT);
        cornerCellContainerLp.gravity= Gravity.CENTER;
        headContainer.addView(cornerCellContainer,cornerCellContainerLp);
        TableAdapter.ViewHolder cornerCellViewHolder=tableAdapter.onCreateCornerCellViewHolder(cornerCellContainer);
        cornerCellContainer.addView(cornerCellViewHolder.itemView);
        tableAdapter.onBindCornerCellViewHolder(cornerCellViewHolder);


        final TableRowView  topRowView=new TableRowView(context);
        topRowView.setScrollChangedListener(this);
        LinearLayout.LayoutParams  topRowViewContainerLp=new LinearLayout.LayoutParams(0,LayoutParams.MATCH_PARENT);
        topRowViewContainerLp.gravity=Gravity.CENTER;
        topRowViewContainerLp.weight=1;
        headContainer.addView( topRowView, topRowViewContainerLp);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(context,RecyclerView.HORIZONTAL,false);
        topRowView.setLayoutManager(linearLayoutManager);
        topRowView.addItemDecoration(new RecycleViewDivider(context,VERTICAL));

        headAdapter=new RecyclerView.Adapter() {
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                RecyclerView.ViewHolder viewHolder=tableAdapter.onCreateTopCellViewHolder(parent);
                return viewHolder;
            }

            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
                tableAdapter.onBindTopCellViewHolder(holder,position);
            }

            @Override
            public int getItemCount() {
                return tableAdapter.getCellColumns();
            }
        };
        topRowView.setAdapter(headAdapter);
        rowViews.add(topRowView);
    }

    private ViewGroup initBodyNormalItemView(){
        LinearLayout itemContainer=new LinearLayout(context);
        LinearLayout.LayoutParams itemContainerLp=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
        itemContainer.setLayoutParams(itemContainerLp);

        FrameLayout leftCellContainer=new FrameLayout(context);
        LinearLayout.LayoutParams leftCellContainerLp=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.MATCH_PARENT);
        leftCellContainerLp.gravity= Gravity.CENTER;
        itemContainer.addView(leftCellContainer,leftCellContainerLp);
        TableAdapter.ViewHolder leftCellViewHolder=tableAdapter.onCreateLeftCellViewHolder(leftCellContainer);
        leftCellContainer.addView(leftCellViewHolder.itemView);
        //设置到布局里，在onCreateViewHolder中传递给itemContainer的ViewHolder，便于在bind时候使用
        itemContainer.setTag(leftCellViewHolder);

        final TableRowView  normalRowView=new TableRowView(context);

        LinearLayout.LayoutParams  topRowViewContainerLp=new LinearLayout.LayoutParams(0,LayoutParams.MATCH_PARENT);
        topRowViewContainerLp.gravity=Gravity.CENTER;
        topRowViewContainerLp.weight=1;
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(context,RecyclerView.HORIZONTAL,false);
        normalRowView.setLayoutManager(linearLayoutManager);
        normalRowView.setScrollChangedListener(TableView.this);

        normalRowView.addItemDecoration(new RecycleViewDivider(context,VERTICAL));
        itemContainer.addView( normalRowView, topRowViewContainerLp);
        normalRowView.setFocusableInTouchMode(false);
        rowViews.add(normalRowView);
        return itemContainer;
    }

    @Override
    public void notifyDataChanged() {

        headAdapter.notifyDataSetChanged();
        //因为删除了列，所以刷新
        for(RecyclerView.Adapter rowAdapter:rowAdapters){
            rowAdapter.notifyDataSetChanged();
        }
    }

    /**
     * body部分由ListView构成，ListView的每个item均由table的行头+每一行的内容cell构成
     * 如果有分组需求，item则由不同的itemtype决定布局
     *      如果分组item要求滑动出屏后吸附在顶端，则在body的ListView顶端覆盖一层布局实现
     */

    private RecyclerView.Adapter bodyAdapter;
    private RecyclerView.Adapter headAdapter;
    private List<RecyclerView.Adapter> rowAdapters=new ArrayList<>();

    private int duiqi=0;
    private int kejian=0;

    private void initBodyAdapter(){
        bodyAdapter=new RecyclerView.Adapter() {
            public static  final int ROW_GROUP_ITEM=0;
            public static  final int NORMAL_ITEM=1;
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

                RecyclerView.ViewHolder viewHolder=null;
                switch (viewType){
                    case ROW_GROUP_ITEM:
                        viewHolder=tableAdapter.onCreateGroupRowViewHolder(parent);
                        break;
                    case NORMAL_ITEM:
                        ViewGroup normalItemView=initBodyNormalItemView();
                        viewHolder=new NormalViewHolder(normalItemView,(TableAdapter.ViewHolder)normalItemView.getTag());
                        break;
                    default:break;
                }
                return viewHolder;
            }

            @Override
            public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {

                if(tableAdapter.isGroupView(position)){

                    tableAdapter.onBindGroupRowViewHolder(holder,position);

                }else{

                    tableAdapter.onBindLeftCellViewHolder(((NormalViewHolder)holder).leftCellContainerViewHolder,position);


                    holder.itemView.post(new Runnable() {
                        @Override
                        public void run() {
                            Log.d("YY","position："+position+"对齐时获取子item"+((NormalViewHolder)holder).normalRowView.itemAviable());
                            ((NormalViewHolder)holder).normalRowView.scrollBy(allScrollDx-((NormalViewHolder)holder).normalRowView.getScrollDistance(),0);
                        }
                    });

                    final int rowPosition=position;
                    final RecyclerView.ViewHolder holderOut=holder;
                    RecyclerView.Adapter rowAdapter=new RecyclerView.Adapter() {
                        @Override
                        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                            RecyclerView.ViewHolder viewHolder=tableAdapter.onCreateCellViewHolder(parent);
                            return viewHolder;
                        }

                        @Override
                        public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

                            tableAdapter.onBindCellViewHolder(holder,position,rowPosition);

                        }

                        @Override
                        public int getItemCount() {
                            return tableAdapter.getCellColumns();
                        }
                    };

                    ((NormalViewHolder)holder).normalRowView.setAdapter(rowAdapter);
                    rowAdapters.add(rowAdapter);

                }

            }

            @Override
            public int getItemCount() {
                return tableAdapter.getCellRows();
            }

            @Override
            public int getItemViewType(int position) {
                if (tableAdapter.isGroupView(position)){
                    return ROW_GROUP_ITEM;
                }else{
                    return NORMAL_ITEM;
                }
            }

            class NormalViewHolder extends RecyclerView.ViewHolder{
                private TableAdapter.ViewHolder leftCellContainerViewHolder;
                private View leftCell;
                private TableRowView normalRowView;

                public NormalViewHolder(ViewGroup itemView,TableAdapter.ViewHolder leftCellContainerViewHolder) {
                    super(itemView);
                    this.leftCellContainerViewHolder=leftCellContainerViewHolder;
                    leftCell=((FrameLayout)itemView.getChildAt(0)).getChildAt(0);
                    normalRowView= (TableRowView) itemView.getChildAt(1);
                }
            }
        };

    }


    private TableAdapter.ViewHolder suspensionViewHolder;
    private void initBody(){

        FrameLayout bodyContainer = new FrameLayout(context);
        addView(bodyContainer,LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);


        RecyclerView  recyclerView=new RecyclerView(context);

        recyclerView.setFocusableInTouchMode(true);

        //对齐:
        recyclerView.setItemViewCacheSize(tableAdapter.getCellRows());
        final LinearLayoutManager linearLayoutManager=new LinearLayoutManager(context,RecyclerView.VERTICAL,false);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(new RecycleViewDivider(context,HORIZONTAL));

        initBodyAdapter();
        recyclerView.setAdapter(bodyAdapter);

        bodyContainer.addView(recyclerView,FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT);


        //吸附头部：悬停,在recyclerView之后add，否则被覆盖
        suspensionViewHolder=tableAdapter.onCreateSuspensionViewHolder();
        final LinearLayout suspensionViewContainer = new LinearLayout(context);
        if(suspensionViewHolder!=null){
            View suspensionView=suspensionViewHolder.itemView;
            suspensionViewContainer.addView(suspensionView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            bodyContainer.addView(suspensionViewContainer, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            //如果有悬停，那么初始的时候就应当bind一次设置View值，以覆盖掉group_item
            tableAdapter.onBindSuspensionViewHolder(suspensionViewHolder,0);
        }

        final int[] titleHeight = {0};
        //悬停
        if(suspensionViewHolder!=null){

            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {


                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    int firstVisibleItemPosition=linearLayoutManager.findFirstVisibleItemPosition();
                    View childView = recyclerView.getChildAt(0);
                    if(titleHeight[0] ==0&&tableAdapter.isGroupView(firstVisibleItemPosition)){
                        titleHeight[0] =childView.getHeight();
                    }
                    if(tableAdapter.isPushGroupView(firstVisibleItemPosition)){
                        int bottom = childView.getBottom();
                        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams)suspensionViewContainer.getLayoutParams();
                        if (bottom < titleHeight[0]) {
                            float pushedDistance = bottom - titleHeight[0];
                            params.topMargin = (int) pushedDistance;
                            suspensionViewContainer.setLayoutParams(params);
                        } else {
                            if (params.topMargin != 0) {
                                params.topMargin = 0;
                                suspensionViewContainer.setLayoutParams(params);
                            }
                        }

                    }else{
                        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams)suspensionViewContainer.getLayoutParams();
                        params.topMargin = 0;
                        suspensionViewContainer.setLayoutParams(params);
                    }
                    //在滚动过程中，要保证悬浮View的值和下方覆盖的item所在group值一致
                    tableAdapter.onBindSuspensionViewHolder(suspensionViewHolder,firstVisibleItemPosition);

                }
            });
        }
    }





    //记录滑动值：用于刷新数据后对齐
    private int allScrollDx=0;
    //同步滑动
    @Override
    public void setCurrentTouchView(final TableRowView currentTouchView) {

        for (TableRowView rowView:rowViews){
            rowView.clearOnScrollListeners();
        }
        currentTouchView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                allScrollDx+=dx;
                for (TableRowView rowView:rowViews){
                    if(rowView!=currentTouchView){
                        rowView.scrollBy(dx,dy);
                    }
                }
            }
        });
    }


}
